package server.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * The Class Logger.
 */
public class Logger {

	/** Location of the log file. */
	private final File logFile = new File("log.log");
	
	/** Location of the error log file. */
	private final File errorLogFile = new File("errorLog.log");

	/** The output writers. */
	private Writer regularOutput;
	
	/** The error output. */
	private Writer errorOutput;
	
	/** The date format for logging messages. */
	DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	
	/**
	 * Instantiates a new logger.
	 */
	public Logger(){
		try {
			//append = on
			regularOutput = new BufferedWriter(new FileWriter(logFile, true));
			errorOutput = new BufferedWriter(new FileWriter(errorLogFile, true));
		} catch (IOException e) {
			System.out.println("Error creating log writers.");
		}
		DateFormat startFormat = new SimpleDateFormat("yyyy/MM/dd");
		log("Server start: ========== " + startFormat.format(new Date())
				+ " ==========");
		logError("Server start: ========== " + startFormat.format(new Date())
				+ " ==========");
		
	}

	/**
	 * Writes a message to the log file.
	 * 
	 * @param log
	 * - string to write to logfile.
	 */
	public void log(String log) {
		try {		
			regularOutput.write(dateFormat.format(new Date()) + " : " + log);
			((BufferedWriter) regularOutput).newLine();
			System.out.println(log);
			regularOutput.flush();
		} catch (IOException e) {
			System.out.println("Error while writing log!");
		}
	}
	
	/**
	 * Writes a message to the error log file.
	 *
	 * @param s the s
	 */
	public void logError(String s) {
		try {
			errorOutput.write(dateFormat.format(new Date()) + " : " + s);
			((BufferedWriter) errorOutput).newLine();
			System.out.println(s);
			errorOutput.flush();
		} catch (IOException e) {
			System.out.println("Error while writing error log!");
		}
	}
	
	/**
	 * Closes the bufferedwriters.
	 */
	public void close(){
		try {
			regularOutput.close();
			errorOutput.close();
		} catch (IOException e) {
			System.out.println("Error while closing logger!");
		}
	}
}
